package com.shop.service.impl;

import com.shop.bean.Cart;
import com.shop.dao.CartDao;
import com.shop.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    CartDao cartDao;
    @Override
    public int add(Cart cart) {
        //空加一个商品到购物车
        if (cart.getQuantity()==0){
            cart.setQuantity(1);
        }
        Cart cart_data=getCart(cart);

         if(cart_data==null){
            cart.setQuantity(cart.getQuantity());
            return cartDao.add(cart);
        }else{
            cart.setQuantity(cart_data.getQuantity()+cart.getQuantity());
            return cartDao.edit(cart);
        }
    }

    @Override
    public Cart edit(Cart cart) {
        int number=cart.getQuantity();

        if(number>=99){
            cart.setQuantity(99);
            cartDao.edit(cart);
            throw new RuntimeException("购物车数量不能大于99");
        }
        if(number<=0){
            cart.setQuantity(1);
            cartDao.edit(cart);
            throw new RuntimeException("购物车数量不能小于1");
        }
        cartDao.edit(cart);
        return cart;
    }

    @Override
    public int delete(Cart cart) {
        return cartDao.delete(cart);
    }

    @Override
    public Cart getCart(Cart cart) {
        return cartDao.getCart(cart);
    }

    @Override
    public List<Cart> getCarts(int userid) {
        return cartDao.getCarts(userid);
    }
}
